package com.ngc.mall.common.configure.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.ngc.mall.common.configure.LocalUser;
import com.ngc.mall.common.configure.exception.BusinessException;
import com.ngc.mall.domain.WxUserDomain;
import com.ngc.mall.service.impl.WxAuthenticationServiceImpl;
import com.ngc.mall.util.JwtToken;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * token拦截器 (微信小程序)
 */
public class PermissionInterceptor implements HandlerInterceptor {
    @Resource
    private WxAuthenticationServiceImpl service;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.isEmpty(bearerToken)) {
            throw BusinessException.PERMISSION_NO_ACCESS;
        }
        String tokens[] = bearerToken.split(" ");
        String token = tokens[0];
        Map<String, Claim> map= JwtToken.getClaims(token);
        if(map==null){
            throw BusinessException.PERMISSION_NO_ACCESS;
        }
        this.setThreadLocal(map);
        return true;
    }

    public boolean setThreadLocal(Map<String,Claim> map){
        Long uid=map.get("uid").asLong();
        WxUserDomain user=this.service.getUserById(uid);
        LocalUser.set(user);
        return true;
    }

    public  void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        LocalUser.clear();
    }
}
